繁体   English   中英

AngularJS:指令未触发或不起作用

[英]AngularJS: Directive is not firing or working

新的角度。 所以只是不明白为什么下面的代码和指令不起作用。 我在代码中出现问题的地方。

页面上没有显示商品名称和价格。

几个问题

require:'ngModel',是什么意思?

指令中的控制器是什么?

控制器选件何时触发?

当人们在指令中声明控制器选项时?

请详细分享知识吗?

HTML代码:

<div ng-app="myApp">
  <ul ng-controller="MyController">

    <li my-directive price="item.price" ng-repeat="item in products">
        {{item.name}} &mdash; {{item.price}}
    </li>
  </ul>
</div>

角度控制器:

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

myApp.controller('MyController', function MyController($scope) {

$scope.products = [
    {
        'name' : 'Xbox',
        'clearance' : true,
        'price' : 30.99,
    },
    {
        'name' : 'Xbox 360',
        'clearance' : false,
        'salesStatus' : 'old',
        'price' : 99.99,
    },
    {
        'name' : 'Xbox One',
        'salesStatus' : 'new',
        'price' : 50,
    },
    {
        'name' : 'PS2',
        'clearance' : true,
        'price' : 79.99,
    },
    {
        'name' : 'PS3',
        'salesStatus' : 'old',
        'price' : 99.99,
    },
    {
        'name' : 'PS4',
        'salesStatus' : 'new',
        'price' : 20.99,
    }
    ]
})

角度指令:

myApp.directive('myDirective', function(){
  return {
    scope: { price: '=' },
    require: 'ngModel',
    link : function(scope){
      console.log(scope.price)
      alert('scope price '+scope.price);
    },
    controller: function(scope, element, attrs, ngModel){
      console.log(ngModel.price);
      console.log(scope.price);
      alert('ngModel price '+scope.price);
      alert('scope price '+scope.price);
    },

    template: 'Name: {{item.name}} Address: {{item.price}}'
  }
});

jsfiddle

require:'ngModel',是什么意思?

当您需要another directive控制器时。 在这里,您尝试调用ngModel指令的控制器。

指令中的控制器是什么? 控制器选件何时触发? 当人们在指令中声明控制器选项时?

指令的Controller是在一个人的上下文中定义的,可以将其注入其他指令中以inter-directive communication

这是有关指令生命周期执行的详细信息,可以帮助您更好。 http://odetocode.com/blogs/scott/archive/2014/05/28/compile-pre-and-post-linking-in-angularjs.aspx

您分享的小提琴中有很多错误,更正了一些错误,以打印从view传递到directive以显示的值。 https://jsfiddle.net/6am7xd0r/2/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM