Atarang Atarang - 10 months ago 67
AngularJS Question

AngularJS data binding and view change

I understand how two-way data binding works with AngularJS but I'm struggling to make it work in a situation described below. I've a index.template.html, home.template.html, search.template.html, app.js, search.controller.js and search.service.js files. I've a input form on a home page at '/' url.

<li ng-controller="searchCtrl"> //searchCtrl() in search.controller.js file
<form role="search">
<input type="text" ng-model="searchstring"
placeholder="Enter string here"> <br />
<button type="submit"

And I've search.template.html to display the results as follows,

<h1> SearchedText</h1>
<h2> {{ searchedtext }} </h2>

search.controller.js is as follows,

(function () {
.controller('searchCtrl', searchCtrl);
searchCtrl.$inject = ['$scope', 'SearchService'];

function searchCtrl($scope, SearchService) {
$scope.searchString = function(searchtext) {
.getSearchResults(searchtext) //getSearchResults in search.service.js
.success(function(data) {
console.log('Service call is a success with result:');
$scope.searchedtext = data;
}).error(function(e) {

My app.js file is as follows,

var myApp = angular.module('twowaybindapp', [ 'ngRoute' ]);
myApp.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
when('/', {
templateUrl: 'home.view.html'
when('/search', {
templateUrl: 'search.view.html',
controller: 'searchCtrl'
otherwise({ redirectTo: '/' });

With this background, When I've both form and results html text (content of search.template.html) in the same home.template.html, things work fine and I see all the results but if I put them in separate files as above, either I don't know how to open the results in new view after the call or don't know if data-binding is not working. I do see results in console.log() in both cases that mean service call is working okay as expected. This might be silly question but I really need help with this. Would it work if the search form is a part of navigation directive at the top of every page and results needs to be shown below in a main ng-view? Any help is appreciated. Thanks.
-- Atarangp

Answer Source

When you write {{smth}} in html it parsed to $scope.smth, each controller has its own scope object, by default scopes are nested:

<div ng-controller="c1" ng-init="smth = 1">
    <div ng-controller="c2">
        {{smth}} << 1
<div ng-controller="c3">
    {{smth}} << undefined

When you defined several views - they will have different scopes, so you can not see one scope from another.

Fastest way to make it work is change to $rootScope.searchedtext = data; cause all your scopes nests from root scope.

Other way is to make common parent state and access and set your property there.

Yet another ways are: use your own service to store data, pass data using events, pass data using properties in state obj...