AngularJS:指令没有启动或工作

AngularJS: Directive is not firing or working

本文关键字:启动 工作 指令 AngularJS      更新时间:2024-04-17

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

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

几个问题

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/