我编写了一个需要更新父作用域的angular指令。
angular.module('app').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, element, attributes, model) {
$scope.property1 = 'some val';
$scope.property2 = 'another val';
$scope.$apply();
};
});
但在我的控制器中我这样做:
MyCtrl = function($scope){
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}
当doSave
运行时,我在控制台中收到了未定义的值。如何在不隔离范围的情况下将其应用于父节点范围。我没有此选项,因为同一元素上的另一个指令隔离了作用域。
答案 0 :(得分:3)
它应该工作。默认情况下,如果未在指令中指定范围,则使用父范围,因此应设置property1和property2。尝试将指令中的范围设置为false。作为旁注并不是一个好的做法,你在做什么。最好隔离范围并将属性添加为属性。这样你就会有很好的封装。
例如
angular.module('app').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
property1: '=',
property2: '='
}
link: function ($scope, element, attributes, model) {
//here you have access to property 1 and 2
};
});
function MyCtrl($scope) {
$scope.property1 = null;
$scope.property2 = null;
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}
和你的HTML
<div ng-control="MyCtrl">
<div google-place property1='property1' property2='property2'></div>
</div>
答案 1 :(得分:1)
我不知道你做错了什么,因为它似乎有效:http://jsfiddle.net/HB7LU/2865/
var myApp = angular.module('myApp',[]);
angular.module('myApp').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, element, attributes, model) {
$scope.property1 = 'some val';
$scope.property2 = 'another val';
$scope.$apply();
}
}
});
angular.module('myApp').controller('MyCtrl', MyCtrl);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}