AngularJS 动态添加元素和删除元素
$scope.userName='Welcome to Angular World!';
$scope.test = function test(){
console.log('Angular 动态添加元素');
}
//通过$compile动态编译html
var html="<div ng-click='test()'>}</div>";
var template = angular.element(html);
var mobileDialogElement = $compile(template)($scope);
angular.element(document.body).append(mobileDialogElement);
// remove移除创建的元素
var closeMobileDialog = function () {
if (mobileDialogElement) {
mobileDialogElement.remove();
}
AngularJS 事件广播与接收:
发送消息: $scope.$emit(name, data) 或者 $scope.$broadcast(name, data);
接收消息: $scope.on(name,function(event,data){ });
区别: $emit 广播给父controller $broadcast 广播给子controller
broadcast 是从发送者向他的子scope广播一个事件。
这里就是ParentController发送, ParentController 和 ChildController 会接受到, 而MainController是不会收到的
$emit 广播给父controller,父controller 是可以收到消息
$on 有两个参数function(event,msg) 第一个参数是事件对象,第二个参数是接收到消息信息
angular.module('onBroadcastEvent', ['ng'])
.controller('MainController', function($scope) {
$scope.$on('To-MainController', function(event, msg) {
console.log('MainController received:' + msg);
});
})
.controller('ParentController', function($scope) {
$scope.click = function(msg) {
$scope.$emit('To-MainController', msg + ',from ParentController to MainController');
$scope.$broadcast('To-ChildController', msg + ',from ParentController to ChildController');
$scope.$broadcast('To-BrotherController', msg + ',from ParentController to BrotherController');
}
})
.controller('ChildController', function($scope) {
$scope.$on('To-ChildController', function(event, msg) {
console.log('ChildController received:' + msg);
});
})
.controller('BrotherController', function($scope) {
$scope.$on('To-BrotherController', function(event, msg) {
console.log('BrotherController received:' + msg);
});
});