AngularJS根范围和隔离范围



下面是我的html和javascript

<div ng-app="myApp" ng-controller="myCtrl">
{{firstname}}
<sample-directive></sample-directive>
</div>

.JS

var app = angular.module("myApp", []);
app.run(function($rootScope){
$rootScope.firstname = "Root scope value"
});
app.controller("myCtrl", function($scope) {
});
app.directive("sampleDirective",function(){
return{
template:"<div>{{firstname}}</div>",
controller:['$scope',sampleDirectiveScope]
};
});
function sampleDirectiveScope($scope){
$scope.firstname = "scope value";
};

我希望"根范围值"显示在表达式中,">范围值">显示在指令标签

为什么它们都显示"范围"值

表达式不应该{{firstname}}从根范围获取值,因为我只在指令的控制器中更改了名字

小提琴

默认情况下,指令的$scope指向其上方的任何范围。使用 scope 属性来调整此设置。

var app = angular.module("myApp", []);
app.run(function ($rootScope) {
$rootScope.firstname = "Root scope"
});
app.controller("myCtrl", function ($scope) {
$scope.lastName = "Doe";
});
app.directive("sampleDirective", function () {
return {
template: "<div>{{firstname}}</div>",
scope: {}, // isolated scope
controller: ['$scope', sampleDirectiveScope]
};
});

使用scope: {}提供了一个独立的作用域,与上述作用域分开。在 {} 中,可以提供要显式传入的属性列表。范围的其他可能值:false(默认值,指向上面的范围)和true(通过原型指向上面的范围)。

更多内容:https://docs.angularjs.org/guide/directive(向下滚动一点,或搜索"隔离范围")

共享作用域是角度指令的默认行为。 有关非常详细和完整的答案,请查看这篇文章: https://stackoverflow.com/a/19775531/3686898

这是您更新的小提琴和新范围:

app.directive("sampleDirective",function(){
return{
template:"<div>{{firstname}}</div>",
scope: {},
controller:['$scope',sampleDirectiveScope]
};
});

https://jsfiddle.net/a1gf9fwc/2/

在你的指令中使用scope: {}

最新更新