geo*_*sic 5 angularjs angularjs-directive angularjs-ng-click
当作用域是在指令上继承时,我可以让 ng-click 工作,但在隔离时不能。 UPDATE: The point is that I want the click function to be defined as part of the directive... moving the function definition into a different scope is not what I want.
这是具有继承范围的工作示例:https : //codepen.io/anon/pen/PGBQvj
这是具有隔离范围的破碎示例; https://codepen.io/anon/pen/jrpkjp
(单击数字,它们在第一个示例中递增,但在第二个示例中不递增)
一些代码...
HTML
<div ng-app="myApp" ng-controller="baseController">
<my-directive ng-click="hello()" current="current"></my-directive>
</div>
Run Code Online (Sandbox Code Playgroud)
具有继承范围的指令:
angular.module('myApp', [])
.controller('baseController', function($scope) {
$scope.current = 1;
})
.directive('myDirective', function() {
return {
link: function(scope, element, attrs) {
scope.hello = function() {
scope.current++
};
},
replace: true,
scope: true,
template: '<div><child> <strong>{{ current }}</strong></child></div>'
}
})
.directive('child', function() {
return {
link: function(scope, element, attrs) {
console.log("horeee");
}
}
});
Run Code Online (Sandbox Code Playgroud)
相同的指令但具有独立的作用域:
angular.module('myApp', [])
.controller('baseController', function($scope) {
$scope.current = 1;
})
.directive('myDirective', function() {
return {
link: function(scope, element, attrs) {
scope.hello = function() {
scope.current++
};
},
replace: true,
scope: {
current:'='
},
template: '<div><child> <strong>{{ current }}</strong></child></div>'
}
})
.directive('child', function() {
return {
link: function(scope, element, attrs) {
console.log("horeee");
}
}
});
Run Code Online (Sandbox Code Playgroud)
问题是你试图调用一个未定义的函数。如果您希望在独立指令内定义逻辑,则无需传入函数引用。
<my-directive current="current"></my-directive>
Run Code Online (Sandbox Code Playgroud)
你不能通过ng-click="hello()"这里。这是控制器的范围,因此hello()未定义。
相反,将ng-click事件移至指令模板
template: '<div ng-click="hello()">
Run Code Online (Sandbox Code Playgroud)
另外一点:您正在使用link()该指令的功能。这是为 DOM 操作保留的。相反,在函数hello()内定义controller。
controller: function ($scope) {
$scope.hello = function() {
$scope.current++
}
},
Run Code Online (Sandbox Code Playgroud)
不过,我认为这里存在一个更大的架构问题。独立指令或组件的要点是将逻辑封装在其自身内部。它不应该操纵外部状态。在此示例中,您将增加一个数字。如果在应用程序的另一部分中您希望减少一个数字怎么办?使用递减逻辑复制指令会导致大量代码重复。
相反,您应该在控制器中定义增量或减量功能,并将其传递给指令。
<my-directive change-number="increment()" current="current"></my-directive>
Run Code Online (Sandbox Code Playgroud)
然后,使用&语法将函数引用绑定到指令:
scope: {
current:'=',
changeNumber: '&'
},
Run Code Online (Sandbox Code Playgroud)
并changeNumber从模板中调用。这样做非常有利于代码的重用。