2014-05-01 114 views
1

我在理解如何實例化隔離範圍上的值時遇到了一些麻煩。實例化隔離範圍上的值

該示例中的代碼可以找到here

testA由於我們有控制器設置$scope.name$scope.alt我期望看到AltA和Sam的名稱。相反alt不可用,並且name來自父項目。

testB按預期工作。我們有一個繼承範圍。

testC也不能按預期方式工作,因爲我們預計該名稱來自name屬性,而是使用根控制器上的name

對我的概念錯誤的地方有幫助嗎?

HTML:

<div ng-controller="RootController"> 
    <h1>name on RootController = {{ name }}</h1> 

    <div test-a="test-a"> 
    <h1>TestA</h1> 
    <h2>name is: {{ name }}, expected is Sam</h2> 
    <h2>alt is: {{ alt }}, expected AltA</h2> 
    </div> 

    <div test-b="test-b"> 
    <h1>TestB</h1> 
    <h2>name is: {{ name }}, expected is Dave</h2> 
    <h2>scope.alt is: {{ alt }}, expected is AltB</h2> 
    </div> 

    <div test-c="test-c" name="Homer"> 
    <h1>TestC</h1> 
    <h2>name is: {{ name }}, expect Homer</h2> 
    </div> 
</div> 

JS:

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



app.controller('RootController', function($scope) { 

    //this is set first... 
    $scope.name = "Bob"; 

}); 

// Isolate scope, but why is name not working in controller instantiation 
app.directive('testA', function() { 
    return { 
    restrict: 'A', 
    scope: {}, 
    controller: function($scope) { 
     $scope.name = "Sam"; // Instead it's using value from parent scope 
     $scope.alt = "AltA"; // Can't be acccessed? 
    } 
    }; 
}); 

// Inherited scope, works as expected 
app.directive('testB', function() { 
    return { 
    restrict: 'A', 
    scope: true, 
    controller: function($scope) { 
     $scope.name = 'Dave'; // Overwrites the value on our scope, like we expect 
     $scope.alt = "AltB"; // Sets this on our scope, like we expect 
    } 
    }; 
}); 

// Isolate scope, name instantiated from attr 
app.directive('testC', function() { 
    return { 
    restrict: 'A', 
    scope: { name: '@' } 
    }; 
}); 

回答

2

這是你plunkr的工作叉:http://plnkr.co/edit/Oecr5F2tcyioS30g2mYG?p=preview

你需要把模板與分離範圍的指令,或使用transclude。

這是我改變了對你的第一個指令,例如:

app.directive('testA', function() { 
    return { 
    restrict: 'A', 
    template: '<div><h1>TestA</h1><h2>name is: {{ name }}, expected is Sam</h2><h2>alt is: {{ alt }}, expected AltA</h2></div>', 
    scope: {}, 
    link: function($scope, elem, attrs) { 
     $scope.name = "Sam"; // Instead it's using value from parent scope 
     $scope.alt = "AltA"; // Can't be acccessed? 
    } 
    }; 
}); 
+0

這使得總的感覺,不知道爲什麼我沒有意識到這一點。一直在我的頭上撞了太久。 – Ryan