javascript - AngularJS 在工厂中创建元素

标签 javascript html angularjs

我目前正在学习 AngularJS,我想创建一个通知模块,但我找不到任何帮助教程。

我希望所有通知都添加到一个 div 中,我需要首先创建它。这是我的第一个问题。我必须在哪里将元素附加到 DOM 中,这样代码仍然是有效的 Angular 代码。

<!DOCTYPE html>
<html>
    <head>
        ...
    </head>
    <body>
        ...
        <div class="notification-center"> //Element I need to create
            ... //Notifications come here
        </div>
    </body>
</html>

我通过在 module.run() 函数中附加 div 解决了这个问题,但不知何故我认为它不应该在那里

var notification = angular.module('notification', []);

notification.run([function(){
    var el = angular.element('#notificationcenter');

    if(!angular.element(el).length){
        el = angular.element('<div>').attr('id', 'notificationcenter').text('{{ text }}').appendTo(angular.element('body'));
    }
}]);

为了创建通知,我编写了一个工厂,在 #notificationcenter div 中附加另一个 div。

notification.factory('notification', [function(){
    var defaults = {
        duration: 5000
    };

    return function(text, settings){
        var element = angular.element('<div>').addClass('notification').text(text).appendTo(angular.element('#notificationcenter'));
    };
}]);

基本上这也有效,但是当我想为通知创建指令时,它不会应用。我见过使用 $compile 方法完成的示例,但它总是发生在另一个指令或 Controller 内,因为需要作用域,而我在工厂内没有作用域。

我做错了什么?

最佳答案

定义一个 Controller ,它维护一组通知:

  notification.controller('NotificationController', function() {
      var ctrl = this;
      ctrl.notificationArray = [ ];
      ctrl.addNote = function (note) {
          ctrl.notificationArray.push(ctrl.notificationArray.length + ". " + note);
      };
  });

然后在 HTML 中,对此数组执行 ng-repeat:

    <div ng-controller="NotificationController as ctrl">
        <div class="notification-center" ng-if="ctrl.notificationArray.length>0">
            <div class="notification" ng-repeat="note in ctrl.notificationArray">
               {{note}}
            </div>
        </div>
        <button ng-click="ctrl.addNote('another note');">Add note</button>
    </div>

关于javascript - AngularJS 在工厂中创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33357316/

相关文章:

JavaScript 图像切换点击

javascript - 我怎样才能禁止点击表格的 td?

html - 适合 Firefox 的 960.gs 插件?

javascript - 加载图像后移动应用程序 "unable to load previous operation due to low memory"?

javascript - Laravel 4 无法从 Angular Ajax 获取数据

Angular js : how to use key of object to retrieve value of another json object

Javascript 根据另一个文本框的输入更新文本框

javascript - Aurelia:同构?

javascript - 使用 JavaScript 调用先前的输入值,在另一个 div 标签中显示该值

AngularJS 1.2.1 $injector :modulerr after minifying, 但它在缩小之前运行良好